package tom.client.account;

import java.util.Map;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;

import tom.client.DataForm;
import tom.client.Library;
import tom.client.LookupDialog;
import tom.shared.Account;

public class FormAccount extends DataForm {
	private static FormAccount panel;
	private final TextBox txtDescript;
	private Account record;

	public static FormAccount getPanel() {
		if (panel == null) {
			panel = GWT.create(FormAccount.class);
		}
		return panel;
	}

	public FormAccount() {
		txtCode.setMaxLength(20);
		lbCode.setText("เลขที่บัญชี");

		txtDescript = new TextBox();
		txtDescript.setMaxLength(50);
		add(txtDescript, 121, 117);
		txtDescript.setSize("250px", "18px");

		Label lblNewLabel = new Label("คำอธิบาย");
		add(lblNewLabel, 22, 117);
		setFieldsHandler();
	}

	@Override
	protected void search() {
		LookupDialog.show("เลขที่บัญชี", "accCode", txtCode);
	}

	@Override
	protected void refresh() {
		Library.getAccService().selectAccount(txtCode.getText(), dataCallback);
	}

	@Override
	protected void update() {
		getFields();
		Library.getAccService().updateAccount(record, delCallback);
	}

	@Override
	protected void insert() {
		getFields();
		Library.getAccService().insertAccount(record, delCallback);
	}

	@Override
	protected void delete() {
		if (Window.confirm("ต้องการลบ " + txtDescript.getText() + " หรือไม่?")) {
			Library.getAccService().deleteAccount(txtCode.getText(),
					delCallback);
		}
	}

	@Override
	protected void clearFields() {
		super.clearFields();
		txtDescript.setText(null);
	}

	@Override
	protected void setFields() {
		super.setFields();
		if (record != null) {
			txtDescript.setText(record.descript);
		} else {
			String code = txtCode.getText();
			clearFields();
			setMode(3);
			txtCode.setText(code);
		}
	}

	@Override
	protected void getFields() {
		if (record == null)
			record = new Account();
		record.accCode = txtCode.getText();
		record.descript = txtDescript.getText();
	}

	@Override
	protected String getReportFile() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected Map<String, Object> genReportParams() {
		// TODO Auto-generated method stub
		return null;
	}

	AsyncCallback<Account> dataCallback = new AsyncCallback<Account>() {

		@Override
		public void onSuccess(Account result) {
			record = result;
			setFields();
		}

		@Override
		public void onFailure(Throwable caught) {
			Window.alert(Library.ERROR_MESSAGE);
		}
	};
}
